import 'package:flutter/material.dart';
import 'package:flutter_demo/chapter7-FunctionWidget/inherted-across-widget/InheritedProvider.dart';

class ChangeNotifierProvider<T extends ChangeNotifier> extends StatefulWidget {
  const ChangeNotifierProvider(
      {Key? key, required this.data, required this.child});

  final Widget child;
  final T data;

//定义一个便捷方法，方便子树中的widget获取共享数据
  static T of<T>(BuildContext context, {bool listen = true}) {
    // final type = _typeOf<InheritedProvider<T>>();
    final provider =  listen ? context.dependOnInheritedWidgetOfExactType<InheritedProvider<T>>()
        : context.getElementForInheritedWidgetOfExactType()?.widget as InheritedProvider;
    return provider!.data;
  }

  @override
  _ChangeNotifierProvider<T> createState() => _ChangeNotifierProvider();

}

class _ChangeNotifierProvider<T extends ChangeNotifier> extends State<ChangeNotifierProvider<T>> {

  void update() => setState(()=>{});

  @override
  void didUpdateWidget(ChangeNotifierProvider<T> oldWidget) {
    if (widget.data != oldWidget.data) {
      oldWidget.data.removeListener(update);
      widget.data.addListener(update);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    widget.data.addListener(update);
    super.initState();
  }

  @override
  void dispose() {
    widget.data.removeListener(update);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return InheritedProvider<T>(
      data: widget.data,
      child: widget.child,
    );
  }
}
